package com.bobbygu.bobbyapp.function.contentprovider

import android.content.ContentValues
import android.net.Uri
import android.view.View
import com.bobbygu.lib.mvvm.common.BaseActivity
import com.bobbygu.lib.mvvm.common.BaseModel
import com.bobbygu.lib.mvvm.common.BaseViewModel
import com.bobbygu.bobbyapp.R
import com.ontbee.legacyforks.cn.pedant.SweetAlert.SweetAlertDialog
import com.orhanobut.logger.Logger
import kotlinx.android.synthetic.main.activity_provider.*
import java.util.*

/**
 * 模拟调用contentProvider,可以在另一个应用使用，修改数据
 * # time: 2017/12/5 10:56
 * # e-mail: gubojun@csii.com.cn
 * @author 顾博君
 * @since 1.0
 */
@Suppress("FINITE_BOUNDS_VIOLATION_IN_JAVA")
class ProviderActivity<VM : BaseViewModel<*, *>, M : BaseModel<*>> : BaseActivity<VM, M>(), View.OnClickListener {
    private var uri = Uri.parse("content://com.bobbygu.contentProvider/teacher")!!
    override fun getLayoutId(): Int = R.layout.activity_provider

    override fun initView() {
        btn_insert.setOnClickListener(this)
        btn_query.setOnClickListener(this)
        btn_query_all.setOnClickListener(this)
        btn_modify.setOnClickListener(this)
        btn_delete.setOnClickListener(this)
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.btn_insert -> {
                val cv = ContentValues()
                cv.put("title", "teacherTitle")
                cv.put("name", "teacher")
                cv.put("sex", true)
                val uri2 = contentResolver.insert(uri, cv)
                SweetAlertDialog(this)
                        .setTitleText(getString(R.string.dialog_title))
                        .setContentText(uri2.toString())
                        .show()
                Logger.d(uri2.toString())
            }
            R.id.btn_query -> {
                // 查找id为1的数据
                val c = contentResolver.query(uri, null, "_ID=?", arrayOf("1"), null)
                //这里必须要调用 c.moveToFirst将游标移动到第一条数据,不然会出现index -1 requested , with a size of 1错误；cr.query返回的是一个结果集。
                if (!c!!.moveToFirst()) {
                    // 为空的Cursor
                    SweetAlertDialog(this, SweetAlertDialog.ERROR_TYPE)
                            .setTitleText(getString(R.string.dialog_title))
                            .setContentText("未找到id=1的数据")
                            .show()
                    return
                }
                val name = c.getColumnIndex("name")
                Logger.d(c.getString(name))
                SweetAlertDialog(this)
                        .setTitleText(getString(R.string.dialog_title))
                        .setContentText(c.getString(name))
                        .show()
                c.close()
            }
            R.id.btn_query_all -> {
                val c = contentResolver.query(uri, null, null, null, null)
                var str = ""
                while (c.moveToNext()) {
                    str += c.getInt(c.getColumnIndex("_id")).toString() +
                            " ${c.getString(c.getColumnIndex("name"))} \n"
                }
                Logger.d("count:${c!!.count} \n$str")
                SweetAlertDialog(this)
                        .setTitleText(getString(R.string.dialog_title))
                        .setContentText("count:${c.count} \n$str")
                        .show()
                c.close()
            }
            R.id.btn_modify -> {
                val cv = ContentValues()
                cv.put("name", "teacherM")
                cv.put("date_added", Date().toString())
                val updatedNum = contentResolver.update(uri, cv, "_ID=?", arrayOf("3"))
                println("updated" + ":" + updatedNum)
                if (updatedNum == 0)
                    SweetAlertDialog(this, SweetAlertDialog.ERROR_TYPE)
                            .setTitleText(getString(R.string.dialog_title))
                            .setContentText("数据更新失败")
                            .show()
                else
                    SweetAlertDialog(this)
                            .setTitleText(getString(R.string.dialog_title))
                            .setContentText("updated" + ":" + updatedNum)
                            .show()
            }
            R.id.btn_delete -> {
                val c = contentResolver.query(uri, null, null, null, null)
                if (!c!!.moveToFirst()) {
                    SweetAlertDialog(this, SweetAlertDialog.ERROR_TYPE)
                            .setTitleText(getString(R.string.dialog_title))
                            .setContentText("数据删除失败")
                            .show()
                    return
                }
                c.moveToLast()
                val index = c.getInt(c.getColumnIndex("_id")).toString()
                contentResolver.delete(uri, "_ID=?", arrayOf(index))
                SweetAlertDialog(this, SweetAlertDialog.SUCCESS_TYPE)
                        .setTitleText(getString(R.string.dialog_title))
                        .setContentText("btn_delete index:$index")
                        .show()
                c.close()
            }
        }
    }

    companion object {

        /**
         * @param activity BaseActivity
         */
        fun startActivity(activity: BaseActivity<*, *>) {
            activity.startActivity(ProviderActivity::class.java)
        }
    }
}